# app/routes.py
from flask import Blueprint, request, jsonify, current_app
from app import db
from models.models import RawNews, ProcessedNews, ProcessingError
from celery_worker import process_news_task
from datetime import datetime

main_bp = Blueprint('main', __name__)

@main_bp.route('/api/news', methods=['POST'])
def add_news():
    """添加新新闻"""
    try:
        data = request.get_json()

        # 验证必需字段
        required_fields = ['title', 'content', 'publish_date']
        for field in required_fields:
            if field not in data:
                return jsonify({'error': f'缺少必需字段: {field}'}), 400

        # 创建原始新闻记录
        news = RawNews(
            title=data['title'],
            content=data['content'],
            publish_date=datetime.fromisoformat(data['publish_date']),
            source=data.get('source'),
            url=data.get('url')
        )

        db.session.add(news)
        db.session.commit()

        # 异步处理新闻
        process_news_task.delay(news.id)

        return jsonify({
            'message': '新闻添加成功',
            'news_id': news.id
        }), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@main_bp.route('/api/news/raw', methods=['GET'])
def get_raw_news():
    """获取原始新闻列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        processed = request.args.get('processed', None, type=lambda x: x.lower() == 'true')

        query = RawNews.query

        if processed is not None:
            query = query.filter(RawNews.processed == processed)

        # 按创建时间倒序排列
        query = query.order_by(RawNews.created_at.desc())

        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False
        )

        return jsonify({
            'news': [news.to_dict() for news in pagination.items],
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page,
            'per_page': per_page
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@main_bp.route('/api/news/processed', methods=['GET'])
def get_processed_news():
    """获取处理后的新闻列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        category = request.args.get('category', None, type=str)
        min_score = request.args.get('min_score', None, type=float)

        query = ProcessedNews.query

        if category:
            query = query.filter(ProcessedNews.category == category)

        if min_score is not None:
            query = query.filter(ProcessedNews.news_score >= min_score)

        # 按评分和创建时间倒序排列
        query = query.order_by(
            ProcessedNews.news_score.desc(),
            ProcessedNews.created_at.desc()
        )

        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False
        )

        return jsonify({
            'news': [news.to_dict() for news in pagination.items],
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page,
            'per_page': per_page
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@main_bp.route('/api/news/processed/<int:news_id>', methods=['GET'])
def get_processed_news_detail(news_id):
    """获取处理后的新闻详情"""
    try:
        news = ProcessedNews.query.get(news_id)
        if not news:
            return jsonify({'error': '新闻未找到'}), 404

        return jsonify(news.to_dict())

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@main_bp.route('/api/news/errors', methods=['GET'])
def get_processing_errors():
    """获取处理错误列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)

        query = ProcessingError.query.order_by(ProcessingError.created_at.desc())
        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False
        )

        return jsonify({
            'errors': [error.to_dict() for error in pagination.items],
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page,
            'per_page': per_page
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@main_bp.route('/api/stats', methods=['GET'])
def get_statistics():
    """获取统计信息"""
    try:
        # 总新闻数
        total_raw_news = RawNews.query.count()
        total_processed_news = ProcessedNews.query.count()
        total_errors = ProcessingError.query.count()

        # 未处理新闻数
        unprocessed_news = RawNews.query.filter(RawNews.processed == False).count()

        # 按分类统计
        category_stats = db.session.query(
            ProcessedNews.category,
            db.func.count(ProcessedNews.id)
        ).group_by(ProcessedNews.category).all()

        # 评分统计
        avg_score = db.session.query(
            db.func.avg(ProcessedNews.news_score)
        ).scalar() or 0

        return jsonify({
            'total_raw_news': total_raw_news,
            'total_processed_news': total_processed_news,
            'total_errors': total_errors,
            'unprocessed_news': unprocessed_news,
            'category_stats': dict(category_stats),
            'average_score': round(float(avg_score), 2)
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@main_bp.route('/api/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    try:
        # 检查数据库连接
        db.session.execute('SELECT 1')

        return jsonify({
            'status': 'healthy',
            'timestamp': datetime.utcnow().isoformat()
        })

    except Exception as e:
        return jsonify({
            'status': 'unhealthy',
            'error': str(e),
            'timestamp': datetime.utcnow().isoformat()
        }), 500
